// routes/cards/findAllByGroup.js
const express = require('express');
const pool = require('../../config/pool'); // 使用连接池
const router = express.Router();
const hadLogin = require('../../middleware/hadLogin');

// 获取所有卡片类型及其对应的卡片
router.get('/', hadLogin, (req, res) => {
    const query = `
        SELECT ct.id AS type_id, ct.type_name, ct.description, ct.image_url, c.id AS card_id, 
            c.face_value, c.redemption_discount, c.image_url, c.is_active
        FROM card_types ct
        LEFT JOIN cards c ON ct.id = c.card_type_id
        ORDER BY ct.id;
    `;

    pool.query(query, (err, results) => {
        if (err) {
            console.error('数据库错误:', err);
            return res.status(500).send({
                code: 0,
                message: '数据库错误',
                success: false
            });
        }

        // 处理结果，构建所需的格式
        const response = [];
        results.forEach(row => {
            const typeIndex = response.findIndex(item => item.id === row.type_id);
            if (typeIndex === -1) {
                // 如果类型不存在，创建新类型对象
                response.push({
                    id: row.type_id,
                    type_name: row.type_name,
                    description: row.description,
                    image_url: row.image_url,
                    cards: []
                });
            }
            // 添加卡片到对应的类型
            if (row.card_id) {
                response[typeIndex === -1 ? response.length - 1 : typeIndex].cards.push({
                    id: row.card_id,
                    face_value: row.face_value,
                    redemption_discount: row.redemption_discount,
                    image_url: row.image_url,
                    is_active: row.is_active
                });
            }
        });
        res.json({
            code: 1,
            message: '查询成功',
            success: true,
            list: response
        });
    });
});

module.exports = router;